from markdown import Markdown
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

# Create your models here.

class Category(models.Model):
  """文章分类"""
  id = models.AutoField(primary_key=True)
  title = models.CharField(max_length=100)
  created = models.DateTimeField(default=timezone.now)
  create_by = models.ForeignKey(
    User,
    null=True,
    on_delete=models.SET_NULL,
    related_name='category_cretor'
  )
  modified = models.DateTimeField(default=timezone.now)
  modifier = models.ForeignKey(
    User,
    null=True,
    on_delete=models.SET_NULL,
    related_name='category_modifier'
  )

class Tag(models.Model):
  """文章标签"""
  id = models.AutoField(primary_key=True)
  text = models.CharField(max_length=30, unique=True)
  created = models.DateTimeField(default=timezone.now)
  modified = models.DateTimeField(default=timezone.now)
  creator = models.ForeignKey(
    User,
    null=True,
    on_delete=models.SET_NULL,
    related_name='tags_creator'
  )
  modifior = models.ForeignKey(
    User,
    null=True,
    on_delete=models.SET_NULL,
    related_name='tags_modifior'
  )

  class Meta:
    ordering = ['-id']
  
  def __str__(self):
    return self.text

class Avatar(models.Model):
  """文章标题图"""
  id = models.AutoField(primary_key=True)
  content = models.ImageField(upload_to='avatar/%Y%m%d')

  created = models.DateTimeField(default=timezone.now)
  modified = models.DateTimeField(default=timezone.now)
  creator = models.ForeignKey(
    User,
    null=True,
    on_delete=models.SET_NULL,
    related_name='avatars_creator'
  )
  modifior = models.ForeignKey(
    User,
    null=True,
    on_delete=models.SET_NULL,
    related_name='avatars_modifior'
  )


# 博客文章 model
class Article(models.Model):
  id = models.AutoField(primary_key=True)
  title = models.CharField(max_length=100)
  body = models.TextField()
  category = models.ForeignKey(
    Category,
    null=True,
    blank=True,
    on_delete=models.SET_NULL,
    related_name='articles'
  )
  
  tags = models.ManyToManyField(
    Tag,
    blank=True,
    related_name='articles'
  )

  avatar = models.ForeignKey(
    Avatar,
    null=True,
    blank=True,
    on_delete=models.SET_NULL,
    related_name='article'
  )

  created= models.DateTimeField(default=timezone.now)
  modified = models.DateTimeField(default=timezone.now)

  author = models.ForeignKey(
    User,
    null=True,
    on_delete=models.CASCADE,
    related_name='articles'
  )

  # 新增方法，将 body 转换为带 html 标签的正文
  def get_md(self):
    md = Markdown(
      extensions=[
        'markdown.extensions.extra',
        'markdown.extensions.codehilite',
        'markdown.extensions.toc',
      ]
    )
    md_body = md.convert(self.body)
    # toc 是渲染后的目录
    return md_body, md.toc

  class Meta:
    ordering = ['-created']

  def __str__(self):
    return self.title
